package cn.hh.steam;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Author huangh
 * @date 2021/09/26
 * @Description:
 */
public class SteamTest2 {

    private static List<Person> list;

    static {
        list = new ArrayList<>();
        list.add(new Person("i", 18, "杭州", 999.9));
        list.add(new Person("am", 19, "温州", 777.7));
        list.add(new Person("iron", 21, "杭州", 888.8));
        list.add(new Person("man", 17, "宁波", 888.8));
    }

    /**
     * 统计
     * @param args
     */
    public static void main(String[] args) {
        // 平均年龄
        Double averageAge = list.stream().collect(Collectors.averagingInt(Person::getAge));
        System.out.println(averageAge);

        // 平均薪资
        Double averageSalary = list.stream().collect(Collectors.averagingDouble(Person::getSalary));
        System.out.println(averageSalary);

        // 其他的不演示了，大家自己看api提示。简而言之，就是返回某个字段在某个纬度的统计结果

        // 有个更绝的，针对某项数据，一次性返回多个纬度的统计结果：总和、平均数、最大值、最小值、总数，但一般用的很少
        IntSummaryStatistics allSummaryData = list.stream().collect(Collectors.summarizingInt(Person::getAge));
        long sum = allSummaryData.getSum();
        System.out.println(sum);
        double average = allSummaryData.getAverage();
        int max = allSummaryData.getMax();
        int min = allSummaryData.getMin();
        long count = allSummaryData.getCount();


        double totalSalary = list.stream().mapToDouble(Person::getSalary).sum();
        System.out.println(totalSalary);
        // java 8 stream version
        /*Optional<BigDecimal> result2 = list.stream()
                // 将user对象的mongey取出来map为Bigdecimal
                //.map(Person::getSalary)
                // 使用reduce聚合函数,实现累加器
                .reduce(BigDecimal.ZERO,(p1,p2) ->{
                    BigDecimal p1B = BigDecimal.valueOf(p1.getSalary());
                    BigDecimal p2B = BigDecimal.valueOf(p2.getSalary());
                    return p1B.add(p2B);
                });
        System.out.println("result2 = "+result2);*/

    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    static class Person {
        private String name;
        private Integer age;
        private String address;
        private Double salary;
    }
}
